package com.tanhua.dubbo.api;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tanhua.dubbo.mappers.UserInfoMapper;
import com.tanhua.model.domain.UserInfo;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Map;

@DubboService
public class UserInfoApiImpl implements UserInfoApi{

    @Autowired
    private UserInfoMapper userInfoMapper;

    /**
     * 新增
     * @param userInfo
     */
    @Override
    public void save(UserInfo userInfo) {
        userInfoMapper.insert(userInfo);
    }

    /**
     * 更新
     * @param userInfo
     */
    @Override
    public void update(UserInfo userInfo) {
        userInfoMapper.updateById(userInfo);
    }

    /**
     * 根据id查询对象
     * @param id
     * @return
     */
    @Override
    public UserInfo findById(Long id) {
        UserInfo userInfo = userInfoMapper.selectById(id);
        return userInfo;
    }

    /**
     * 批量查询用户详情
     * @param userIds
     * @param info
     * @return
     */
    @Override
    public Map<Long, UserInfo> findByIds(List<Long> userIds, UserInfo info) {
        //条件构造器
        QueryWrapper<UserInfo> qw = new QueryWrapper();
        //1、用户id列表 匹配所有id
        qw.in("id",userIds);
        //2、添加筛选条件
        if(info != null) {
            if(info.getAge() != null) {
                //小于传过来的age
                qw.lt("age",info.getAge());
            }
            //等于传过来的性别
            if(!StringUtils.isEmpty(info.getGender())) {
                qw.eq("gender",info.getGender());
            }
            if (!StringUtils.isEmpty(info.getNickname())) {
                qw.eq("nickname", info.getNickname());
            }
        }
        //调用mapper查询
        List<UserInfo> list = userInfoMapper.selectList(qw);
        //hutool工具将list转为map 键是id 值是UserInfo自己
        Map<Long, UserInfo> map = CollUtil.fieldValueMap(list, "id");
        return map;
    }

    /**
     * 分页查询
     * @param page
     * @param pagesize
     * @return
     */
    @Override
    public IPage<UserInfo> findAllUsers(Integer page, Integer pagesize) {
        return userInfoMapper.selectPage(new Page<>(page, pagesize), null);
    }
}
